package com.ict.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.utils.SecurityUtils;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.bean.BeanUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.mapper.SysUserRoleMapper;
import com.ict.system.service.ISysDeptService;
import com.ict.web.constant.Constants;
import com.ict.web.constant.ProjectStatusEnum;
import com.ict.web.controller.file.domain.YzqFile;
import com.ict.web.controller.file.dto.YzqFileDTO;
import com.ict.web.controller.file.service.IYzqFileService;
import com.ict.web.domain.Approval;
import com.ict.web.domain.ContractInformation;
import com.ict.web.domain.ProjectManagement;
import com.ict.web.domain.ReviewTask;
import com.ict.web.dto.ContractInformationAddDto;
import com.ict.web.dto.ContractInformationEditDto;
import com.ict.web.mapper.ContractInformationMapper;
import com.ict.web.msg.domain.SysMsg;
import com.ict.web.msg.util.CreateMsgUtil;
import com.ict.web.service.IApprovalService;
import com.ict.web.service.IContractInformationService;
import com.ict.web.service.IProjectManagementService;
import com.ict.web.service.IReviewTaskService;
import com.ict.web.vo.ContractInformationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同信息--刘杰Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-01
 */
@Service
public class ContractInformationServiceImpl extends ServiceImpl<ContractInformationMapper, ContractInformation> implements IContractInformationService
{
    @Resource
    private ContractInformationMapper contractInformationMapper;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IApprovalService approvalService;
    @Autowired
    private IReviewTaskService reviewTaskService;
    @Resource
    private IYzqFileService fileService;
    @Resource
    private SysUserRoleMapper userRoleMapper;

    /**
     * 查询合同信息--刘杰
     *
     * @param contractId 合同信息--刘杰主键
     * @return 合同信息--刘杰
     */
    @Override
    public ContractInformationVo selectContractInformationByContractId(Long contractId)
    {
        ContractInformation contractInformation = contractInformationMapper.selectContractInformationByContractId(contractId);
        ContractInformationVo contractInformationVo = new ContractInformationVo();
        BeanUtils.copyProperties(contractInformation,contractInformationVo);
        YzqFile fileScoc = fileService.getById(contractInformation.getScannedCopyOfContract());
        YzqFile fileTaf = fileService.getById(contractInformation.getTenderAnnouncementFileId());
        YzqFile fileBwaf = fileService.getById(contractInformation.getBidWinningAnnouncementFileId());
        if(StringUtils.isNotNull(contractInformationVo)){
            contractInformationVo.setScannedCopyOfContract(fileScoc);
            contractInformationVo.setTenderAnnouncementFile(fileTaf);
            contractInformationVo.setBidWinningAnnouncementFile(fileBwaf);
        }

        return contractInformationVo;
    }

    /**
     * 查询合同信息--刘杰列表
     *
     * @param contractInformation 合同信息--刘杰
     * @return 合同信息--刘杰
     */
    @Override
    public List<ContractInformation> selectContractInformationList(ContractInformation contractInformation)
    {
        List<ContractInformation> contractInformations = contractInformationMapper.selectContractInformationList(contractInformation);
        contractInformations.forEach(s->{
            s.setScannedCopyOfContractFile(fileService.getById(s.getScannedCopyOfContract()));
            s.setTenderAnnouncementFile(fileService.getById(s.getTenderAnnouncementFileId()));
            s.setBidWinningAnnouncementFile(fileService.getById(s.getBidWinningAnnouncementFileId()));
        });
        return contractInformations;
    }

    /**
     * 新增合同信息--刘杰
     *
     * @param dto 合同信息--刘杰
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertContractInformation(ContractInformationAddDto dto)
    {
        ContractInformation bean = ContractInformationAddDto.of(dto);
        //新增合同信息-生成对应系统消息
        SysDept sysDept = deptService.selectDeptById(SecurityUtils.getDeptId());
        ProjectManagement projectManagement = projectManagementService.getById(dto.getProId());
        Assert.isTrue(StringUtils.isNotNull(projectManagement),"未找到该项目信息");
        String content=projectManagement.getNickName()+ CreateMsgUtil.SUBMITTED+projectManagement.getName()+CreateMsgUtil.CONTRACT_FILING_SUBMITTED;
        //大数据局收到消息
        List<Long> bigDataId = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA);
        List<Long> bigDataNormalId = userRoleMapper.getUserIdByRoleId(Constants.ROLE_TYPE_BIGDATA_NORMAL);
        bigDataId.addAll(bigDataNormalId);
        bigDataId.forEach(s->{
            CreateMsgUtil.createMsg(content,s,null,CreateMsgUtil.CONTRACT_FILING_SUBMITTED_TITLE, SysMsg.RESOURCE_TYPE_DATA,null, null);
        });
        //同步到项目信息
        projectManagement.setContractId(bean.getContractId());
        //同步文件对象
        ArrayList<YzqFile> yzqFiles = ContractInformationAddDto.toFile(bean, dto);
        fileService.batchInsertFile(yzqFiles);

        ReviewTask reviewTask = reviewTaskService.getById(projectManagement.getReviewTaskId());
        Assert.isTrue(StringUtils.isNotNull(reviewTask),"评审任务不能为空");
        Approval approval = approvalService.getApproval(projectManagement.getProId(), projectManagement.getIsState(),null,null);
        approval.setApprovalNode(ProjectStatusEnum.CONTRACT_FILING_SUBMITTED.get().getNode());
        approval.setApprovalStage(ProjectStatusEnum.CONTRACT_FILING_SUBMITTED.get().getStage());
        approval.setApprovalStatus(ProjectStatusEnum.CONTRACT_FILING_SUBMITTED.get().getStatus());
        String approvalDatabase = yzqFiles.stream().map(s -> s.getId()).collect(Collectors.joining(","));
        approval.setApprovalDatabase(String.join(",",approvalDatabase));
        approval.setEndTime(LocalDateTime.now());
        approval.setApprovalOperator(SecurityUtils.getNickName());
        projectManagement.setIsState(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStatus());
        projectManagement.setNode(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getNode());
        projectManagement.setStag(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStage());
        //新增里程碑管理进程
        approvalService.save(new Approval(IdUtils.snowId(),projectManagement.getProId(),ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStage(),
                ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getNode(), LocalDateTime.now(),null, null,ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStatus(),
                "/",null, null,null, LocalDateTime.now(),Approval.APPROVAL_TYPE_PROJECT_MANAGE));
        reviewTask.setNode(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getNode());
        reviewTask.setNodeStatus(ProjectStatusEnum.MILESTONE_MANAGEMENT_TO_BE_SUBMITTED.get().getStatus());
        projectManagementService.updateById(projectManagement);
        reviewTaskService.updateById(reviewTask);
        approvalService.updateById(approval);
        contractInformationMapper.insert(bean);
        //同步项目数据到项目信息表中
        approvalService.synchronizationProjectInfo(projectManagement);
        return bean.getContractId();
    }

    /**
     * 修改合同信息--刘杰
     *
     * @param contractId 合同信息--刘杰
     * @return 结果
     */
    @Override
    public int updateContractInformation(ContractInformationEditDto dto,Long contractId)
    {
        ContractInformation bean = contractInformationMapper.selectById(contractId);
        BeanUtils.copyProperties(dto,bean);
        bean.setUpdateTime(LocalDateTime.now());
        //更新文件信息
        ArrayList<YzqFile> fileList = new ArrayList<>();
        if(StringUtils.isNotEmpty(bean.getScannedCopyOfContract())){
            YzqFile fileScoc = fileService.getById(bean.getScannedCopyOfContract());
            YzqFileDTO fileScocDTO = dto.getScannedCopyOfContract();
            if(StringUtils.isNotNull(fileScoc)){
                BeanUtils.copyProperties(fileScocDTO,fileScoc);
                fileList.add(fileScoc);
            }else {
                YzqFile file = new YzqFile();
                BeanUtils.copyProperties(fileScocDTO, file);
                file.setId(String.valueOf(IdUtils.snowId()));
                fileService.save(file);
                bean.setScannedCopyOfContract(file.getId());
            }
        }

        if(StringUtils.isNotEmpty(bean.getTenderAnnouncementFileId())){
            YzqFile fileTaf = fileService.getById(bean.getTenderAnnouncementFileId());
            YzqFileDTO fileTafDTO = dto.getTenderAnnouncementFile();
            if(StringUtils.isNotNull(fileTaf)){
                BeanUtils.copyProperties(fileTafDTO,fileTaf);
                fileList.add(fileTaf);
            }else {
                YzqFile file = new YzqFile();
                BeanUtils.copyProperties(fileTafDTO, file);
                file.setId(String.valueOf(IdUtils.snowId()));
                fileService.save(file);
                bean.setTenderAnnouncementFileId(file.getId());
            }
        }

        if(StringUtils.isNotEmpty(bean.getBidWinningAnnouncementFileId())){
            YzqFile fileBwaf = fileService.getById(bean.getBidWinningAnnouncementFileId());
            YzqFileDTO fileBwafDTO = dto.getBidWinningAnnouncementFile();
            if(StringUtils.isNotNull(fileBwaf)){
                BeanUtils.copyProperties(fileBwafDTO,fileBwaf);
                fileList.add(fileBwaf);
            }else {
                YzqFile file = new YzqFile();
                BeanUtils.copyProperties(fileBwafDTO, file);
                file.setId(String.valueOf(IdUtils.snowId()));
                fileService.save(file);
                bean.setBidWinningAnnouncementFileId(file.getId());
            }
        }

        fileService.updateBatchById(fileList);
        return contractInformationMapper.updateById(bean);
    }

    /**
     * 删除合同信息--刘杰信息
     *
     * @param contractId 合同信息--刘杰主键
     * @return 结果
     */
    @Override
    public int deleteContractInformationByContractId(Long contractId)
    {
        ContractInformation bean = contractInformationMapper.selectById(contractId);
        bean.setDelFlag("1");
        return contractInformationMapper.updateById(bean);
    }
}
